<?php

namespace app\admin\controller\coursetable;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
/**
 * 
 *
 * @icon fa fa-file
 */
class Classplant extends Backend
{
    
    /**
     * Classplant模型对象
     */
    protected $model = null;
    protected $noNeedRight=["lists","status","export","export2","edit"];
    protected $noNeedLogin=["lists","status","export","export2","edit"];


    public function _initialize()
    {
        parent::_initialize();
        $this->shopid=false;
        $this->model = model('Classplant');
        $this->modelValidate = true;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $tb=model("Coursetable")->where("id","=",$this->request->param("table_id"))->select();
            if($tb) {
                $tb = $tb[0];
                $ids=explode(",",$tb['classes_id']);
//                for($i=0;$i<count($ids);$i++) {
//                    //$classes=model("Classes")->where("status","=",1)->where("id","=",$ids[$i])->find();
//                    $classes=model("Classes")->alias("c")
//                        ->join("fa_course_classroomeplan r","r.classes_id=c.id ","left")
//                        ->where("r.status","=",1)
//                        ->where("c.status","=",1)
//                        ->where("c.id","=",$ids[$i])->find();
//                    if($classes&&!empty($classes)){
//                        $ocouser_count=0;
//                        $ocation_type = 1;
//                        if(preg_match("/舞|瑜伽|太极|礼仪|仪态|八段锦/",$classes['name'])){
//                            $ocation_type=3;
//                        }elseif(preg_match("/书|画/",$classes['name'])) {
//                            $ocation_type = 2;
//                        }elseif(preg_match("/声乐|摄影|器乐|古筝/",$classes['name'])) {
//                            $ocation_type = "1,4,3";
//                        }else{
//                            $ocation_type = 1;
//                        }
//                        if($classes['addresslv_id']==2){
//                            $ocouser_count=17;
//                        }else if($classes['addresslv_id']==3){
//                            $ocouser_count=8;
//                        }else{
//                            $ocouser_count=12;
//                        }
//                        $data=array(
//                            "classes_id"=>$ids[$i],
//                            "table_id"=>$tb['id'],
//                            "subject_lv"=>$classes['subject_lv'],
//                            "addresslv_id"=>$classes['addresslv_id'],
//                            "classes_per_week"=>1,
//                            "same_classroom"=>1,
//                            "same_ocation"=>1,
//                            "can_same_day"=>0,
//                            "daytime"=>"1,3",
//                            "status"=>"1",
//                            "ocourse_count"=>$ocouser_count,
//                            "ocation_type"=>$ocation_type,
//                        );
//                        model("Classplant")->insertUpdate($data,["table_id","classes_id"],false);
//                    }
//                }
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where="";
            $total = $this->model->alias("classplant")->join("eb_classes classes", "classplant.classes_id=classes.id","left")
                ->join("fa_course_classroomeplan r","r.classes_id=classplant.classes_id","left")
                ->where("classplant.status", "=", 1)
                ->field("classplant.*,classes.name,r.ocation_id,r.week,r.daytime");
            $total = $total->where("classplant.status", "<>", -1);
            $total = $total->where("classplant.classes_id", "in", $ids);
            if(isset($_REQUEST['search'])&&$_REQUEST['search']){
                $total = $total->where("classes.name", "like", "%" . $_REQUEST['search'] . "%");
            }
            $total = $total
                ->count();
            $list = $this->model->alias("classplant")->join("eb_classes classes", "classplant.classes_id=classes.id","left")
                ->join("fa_course_classroomeplan r","r.classes_id=classplant.classes_id","left")
                ->where("classplant.status", "=", 1)
                ->field("classplant.*,classes.name,classes.price,classes.num,r.ocation_id,r.week,r.daytime");
            if(isset($_REQUEST['search'])&&$_REQUEST['search']){
                $list = $list->where("classes.name", "like", "%" . $_REQUEST['search'] . "%");
            }
            $list = $list->where("classplant.classes_id", "in", $ids);
            //if ($_SESSION['think']['admin']['group_id'] == 2) {
            //    $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            //}
            $list = $list->where("classplant.status", "<>", -1)
                ->order('weigh desc,classplant.id desc')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            //$this->model->getLastSql();
            $list = collection($list)->toArray();
            function bool($int){
                return $int?"是":"否";
            }
            for($i=0;$i<count($list);$i++){
                $list[$i]['classes_id']=model("Classes")->getClasses_idTextAttr($list[$i]['classes_id'],$list[$i])."({$list[$i]['classes_id']})";
                $list[$i]['subject_lv']=model("Subjectlv")->getSubject_lvTextAttr($list[$i]['subject_lv'],$list[$i]);
                $list[$i]['ocation_type']=model("Ocation")->getOcation_typeTextAttr($list[$i]['ocation_type'],$list[$i]);
                if($list[$i]['teacher_id']){
                    $list[$i]['teacher_id']=model("User")->getTeacher_idTextAttr($list[$i]['teacher_id'],$list[$i]);
                }else{
                    $list[$i]['teacher_id']=$list[$i]['teacher_new'];
                }
                if($list[$i]['manager_id']){
                    $list[$i]['manager_id']=model("User")->getTeacher_idTextAttr($list[$i]['manager_id'],$list[$i]);
                }else{
                    $list[$i]['manager_id']=$list[$i]['manager_new'];
                }
                $list[$i]['disable_week_range']=$this->model->getDisable_week_rangeTextAttr($list[$i]['disable_week_range'],$list[$i]);
                $list[$i]['must_week_range']=$this->model->getMust_week_rangeTextAttr($list[$i]['must_week_range'],$list[$i]);
                $list[$i]['ocation_id']=model("Ocation")->getOcation_idTextAttr($list[$i]['ocation_id'],$list[$i])."({$list[$i]['ocation_id']})";
                $list[$i]['start_date']=isset($list[$i]['start_date'])&&$list[$i]['start_date']!=null?substr($list[$i]['start_date'],0,10) ?? 0:date("Y-m-d");
                // 处理周几字段
                if(isset($list[$i]['week']) && $list[$i]['week']){
                    $weekMap = ['1'=>'周一', '2'=>'周二', '3'=>'周三', '4'=>'周四', '5'=>'周五', '6'=>'周六', '7'=>'周日'];
                    $weeks = explode(',', $list[$i]['week']);
                    $weekNames = [];
                    foreach($weeks as $w){
                        if(isset($weekMap[$w])){
                            $weekNames[] = $weekMap[$w];
                        }
                    }
                    $list[$i]['week'] = join(',', $weekNames);
                }
                

                $list[$i]['can_same_day']=bool($list[$i]['can_same_day']);
                $list[$i]['same_classroom']=bool($list[$i]['same_classroom']);
                $list[$i]['same_ocation']=bool($list[$i]['same_ocation']);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assignconfig("relType",$_REQUEST['relType']);
        $this->assignconfig("table_id",$_REQUEST['table_id']);
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        //$this->model->validate($validate);
                    }
                    //班级是否已经有课程安排
                    $classplant=model("Classplant")->where("classes_id",$params['classes_id'])->where("status",1)->find();
//                    if($classplant){
//                        $this->error("该班级已经有课程安排");
//                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['create_time']=$datatime;
                    unset($params['delete_time']);
                    unset($params['update_time']);
//                    if($_SESSION['think']['admin']['group_id']==2){
//                        $params['city_id']=$_SESSION['think']['admin']['city_id'];
//                    }
                    $params['exclint_day']=(!array_key_exists("exclint_day",$params)||$params['exclint_day']=="")?date("Y-m-d",time()):date("Y-m-d",strtotime($params['exclint_day']));
                    $params['daytime']=join(",",$params['daytime']);
                    $params['daytimeall']=join(",",$params['daytimeall']);
                    $params['disable_week_range']=join(",",$params['disable_week_range']);
                    $params['must_week_range']=join(",",$params['must_week_range']);
                    $params['ocation_type']=join(",",$params['ocation_type']);
                    $params['teacher_id']=join(",",$params['teacher_id']);
                    $params['manager_id']=join(",",$params['manager_id']);
                    $params['table_id']=$params['table_id'];
                    $params['start_date']=isset($params['start_date'])&&$params['start_date']!=null?substr($params['start_date'],0,10) ?? 0:date("Y-m-d");

                    // 处理 teacher_new 和 manger_new 字段
                    if(isset($params['teacher_new']) && $params['teacher_new'] !== "") {
                        $classes['teacher_id'] = $params['teacher_new'];
                    }
                    if(isset($params['manager_id']) && $params['manager_id'] !== "") {
                        $classes['manager_id'] = $params['manager_id'];
                    }
                    if(isset($params['num']) && $params['num'] !== "") {
                        $classes['num'] = $params['num'];
                    }
                    if(isset($params['price']) && $params['price'] !== "") {
                        $classes['price'] = $params['price'];
                    }
                    unset($params['addresslv_id']);
                    unset($params['table_id']);
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        if(array_key_exists("teacher_id",$classes)&&$classes['teacher_id']!=""&&!is_int($classes['teacher_id'])){
                            unset($classes['teacher_id']);
                        }
                        if(array_key_exists("manager_id",$classes)&&$classes['manager_id']!=""&&!is_int($classes['manager_id'])){
                            unset($classes['manager_id']);
                        }
                        model("Classes")->where("id",$params['classes_id'])->update($classes);
                        $this->success("添加成功",null,["refresh"=>true]);
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        // 生成 leftOptions 和 rightOptions 的数据
        $userModel = model('User');
        $data = array("args" => [[], [], []]);
        $leftOptionsData = $userModel->getUserLists($data);
        $leftOptions = ($leftOptionsData == null) ? [] : $leftOptionsData["leftOptions"];
        $rightOptionsData = $userModel->getUserLists();
        $rightOptions = ($rightOptionsData == null) ? [] : $rightOptionsData["list"];
        $this->assignconfig("leftOptions", $leftOptions);
        $this->assignconfig("rightOptions", $rightOptions);
        $this->assign("table_id",$_REQUEST['table_id']);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $classes_id=$this->request->get("classes_id",0);
        $table_id=$this->request->get("table_id",0);
        if($classes_id){
            $classes=model("Classes")->where("id",$classes_id)->find();
            $row=model("Classplant")->alias("classplant")->join("eb_classes c","c.id=classplant.classes_id","left")->field("classplant.*,classplant.id as classplant_id")->where("classes_id",$classes_id)->find();
            if(!$row){
                $plantData=array();
                $plantData["classes_id"]=$classes_id;
                $plantData["price"]=0;
                $plantData["status"]=1;
                $plantData["ocation_type"]="1,2,3,4";
                $plantData["daytime"]="1,3";
                $plantData["classes_per_week"]="1";
                $plantData["ocourse_count"]="12";
                $plantData["same_classroom"]=1;
                $plantData["same_ocation"]=1;
                $plantData["table_id"]=$classes['table_id'] ?? $table_id;
                model("Classplant")->save($plantData);
                $row = model("Classplant")->where("classes_id",$classes_id)->find();
            }else{
                $ids=$row['classplant_id'];
            }
            if($row['table_id']==0||$row['table_id']==null){
                $row['table_id']=$classes['table_id'] ?? 0;
                model("Classplant")->where("classes_id",$classes_id)->update(["table_id"=>$row['table_id']]);
            }
        }else{
            $row = $this->model->get($ids);
            if($row){
                $classes=model("Classes")->where("id",$row['classes_id'])->find();
                $row['table_id']=$classes['table_id'] ?? $table_id;
                $row['price']=$classes['price'] ?? 0;//以classes的价格为准
                $row['num']=$classes['num'] ?? 0; //以classes的招生人数为准
                $row['start_date']=isset($row['start_date'])&&$row['start_date']!=null?substr($row['start_date'],0,10) ?? 0:date("Y-m-d");
                $classes_id=$row['classes_id'];
                if($row['table_id']==0||$row['table_id']==null){
                    $coursetableQuery = model("Coursetable")
                        ->where("classes_id", "like", "%," . $row["id"] . ",%")
                        ->whereOr("classes_id", "like", "%," . $row["id"])
                        ->whereOr("classes_id", "like", $row["id"] . ",%")
                        ->whereOr("classes_id", "=", $row["id"])
                        ->find();
                    if($coursetableQuery&&$coursetableQuery["id"]){
                        $row['table_id']=$coursetableQuery["id"];
                    }
                    $this->model->where("id", "=", $ids)->update(["table_id"=>$row['table_id']]);
                    db::name("fa_course_table_classplant")->where("id", "=", $ids)->update(["table_id"=>$row['table_id']]);
                }
            }
        }

        $address_lv=$classes['addresslv_id'] ?? 0;
        if (!$row)
            $this->error(__('No Results were found'));
            $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            // 如果有data字段，直接使用它
            $classes=array();
            if($classes_id&&$classes_id>0){
                $classes["id"]=$classes_id;
            }
            // 否则使用标准方式获取row数据
            $params = $this->request->post("row/a");
            if (isset($_POST['row'])) {
                $params = $_POST['row'];
            }else  if (isset($_POST['data'])) {
                $params = json_decode($_POST['data'], true);
            }
            // 处理 teacher_new 和 manger_new 字段
            if(isset($params['teacher_new']) && $params['teacher_new'] !== "") {
                $classes['teacher_id'] = $params['teacher_new'];
            }
            if(isset($params['manger_new']) && $params['manger_new'] !== "") {
                $classes['manager_id'] = $params['manger_new'];
            }
            if(isset($params['num']) && $params['num'] !== "") {
                $classes['num'] = $params['num'];
            }
            if(isset($params['price']) && $params['price'] !== "") {
                $classes['price'] = $params['price'];
             }

            // 记录调试信息
            error_log("Extracted params: " . print_r($params, true));
            
            if ($params && is_array($params) && count($params) > 0) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        //$row->validate($validate);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['update_time']=$datatime;
                    unset($params['delete_time']);
                    unset($params['create_time']);
                    // 处理数组字段，过滤空值后转为逗号分隔字符串
                    if(isset($params["teacher_id"]) && is_array($params["teacher_id"])) {
                        $params['teacher_id'] = join(",", array_filter($params["teacher_id"], function($v) { return $v !== ''; }));
                    } else {
                        $params['teacher_id'] = $params["teacher_id"] ?? "";
                    }
                    
                    if(isset($params["manager_id"]) && is_array($params["manager_id"])) {
                        $params['manager_id'] = join(",", array_filter($params["manager_id"], function($v) { return $v !== ''; }));
                    } else {
                        $params['manager_id'] = $params["manager_id"] ?? "";
                    }
                    
                    $params['address_lv']=$address_lv;
                    $params['exclint_day']=(!array_key_exists("exclint_day",$params)||$params['exclint_day']=="")?date("Y-m-d",time()):date("Y-m-d",strtotime($params['exclint_day']));
                    
                    // 处理其他数组字段
                    if(isset($params['daytime']) && is_array($params['daytime'])) {
                        $params['daytime'] = join(",", array_filter($params['daytime'], function($v) { return $v !== ''; }));
                    } else {
                        $params['daytime'] = $params['daytime'] ?? "";
                    }
                    
                    if(isset($params['daytimeall']) && is_array($params['daytimeall'])) {
                        $params['daytimeall'] = join(",", array_filter($params['daytimeall'], function($v) { return $v !== ''; }));
                    } else {
                        $params['daytimeall'] = $params['daytimeall'] ?? "";
                    }
                    
                    if(isset($params['disable_week_range']) && is_array($params['disable_week_range'])) {
                        $params['disable_week_range'] = join(",", array_filter($params['disable_week_range'], function($v) { return $v !== ''; }));
                    } else {
                        $params['disable_week_range'] = $params['disable_week_range'] ?? "";
                    }
                    
                    if(isset($params['must_week_range']) && is_array($params['must_week_range'])) {
                        $params['must_week_range'] = join(",", array_filter($params['must_week_range'], function($v) { return $v !== ''; }));
                    } else {
                        $params['must_week_range'] = $params['must_week_range'] ?? "";
                    }
                    
                    if(isset($params['ocation_type']) && is_array($params['ocation_type'])) {
                        $params['ocation_type'] = join(",", array_filter($params['ocation_type'], function($v) { return $v !== ''; }));
                    } else {
                        $params['ocation_type'] = $params['ocation_type'] ?? "";
                    }
                    if(isset($params['start_date'])&&$params['start_date']!="")$params['start_date']=$params['start_date'];

                    unset($params['addresslv_id']);
                    unset($params['table_id']);
                    $result = $row->allowField(true)->save($params);
                    model("Classes")->where("id", "=", $classes_id)->update(["count_total" => $params["ocourse_count"], "count" => $params["ocourse_count"]]);
                    $updateData = [];
                    if (isset($params['ocation_type']) && $params['ocation_type'] !== '' && $params['ocation_type'] !== null) {
                        $updateData['classroom_type'] = $params['ocation_type'];
                    }
                    if (isset($params['teacher_id']) && $params['teacher_id'] !== '' && $params['teacher_id'] !== null) {
                        $updateData['teacher_id'] = $params['teacher_id'];
                    }
                    if (isset($params['ocourse_count']) && $params['ocourse_count'] !== '' && $params['ocourse_count'] !== null) {
                        $updateData['count_total'] = $params['ocourse_count'];
                        $updateData['count'] = $params['ocourse_count'];
                    }
                    if (isset($params['manager_id']) && $params['manager_id'] !== '' && $params['manager_id'] !== null) {
                        $updateData['manager_id'] = $params['manager_id'];
                    }
                    if(isset($params['num']) && $params['num'] !== '' && $params['num'] !== null) {
                        $updateData['num'] = $params['num'];
                    }
                    if (isset($params['price']) && $params['price'] !== '' && $params['price'] !== null) {
                        $updateData['price'] = $params['price'];
                    }
                    if (!empty($updateData)) {
                        if(isset($classes['teacher_id'])){
                            unset($classes['teacher_id']);
                        }
                        if(isset($classes['manager_id'])){
                            unset($classes['manager_id']);
                        }
                        db::name("eb_classes")->where("id", $classes["id"])->update($classes);
                    }
                    if ($result !== false) {
                        $this->success("编辑成功",null,["refresh"=>true]);
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $r=model("classes")->where("id",$row['classes_id'])->find();
        if(isset($_SESSION['think']['admin'])){
            $this->assignconfig("admin",$_SESSION['think']['admin']);
            $city_id=$_SESSION['think']['admin']['city_id'];
            $address_lv=0;
            $school_id=$_SESSION['think']['admin']['school_id'];
            $community_id=$_SESSION['think']['admin']['community_id'];
        }
        $row = $this->model->get($ids);
        if($row){
            $classes=model("Classes")->where("id",$row['classes_id'])->find();
            $row['table_id']=$classes['table_id'] ?? 0;
            $row['price']=$classes['price'] ?? 0;//以classes的价格为准
            $row['num']=$classes['num'] ?? 0; //以classes的招生人数为准
            if($row['table_id']==0||$row['table_id']==null){
                $coursetableQuery = model("Coursetable")
                    ->where("classes_id", "like", "%," . $row["id"] . ",%")
                    ->whereOr("classes_id", "like", "%," . $row["id"])
                    ->whereOr("classes_id", "like", $row["id"] . ",%")
                    ->whereOr("classes_id", "=", $row["id"])
                    ->find();
                if($coursetableQuery&&$coursetableQuery["id"]){
                    $row['table_id']=$coursetableQuery["id"];
                }
                $this->model->where("id", "=", $ids)->update(["table_id"=>$row['table_id']]);
                db::name("fa_course_table_classplant")->where("id", "=", $ids)->update(["table_id"=>$row['table_id']]);
            }
        }
        $row['start_date']=isset($row['start_date'])&&$row['start_date']!=null?substr($row['start_date'],0,10) ?? 0:date("Y-m-d");


        $this->view->assign("row", $row);
        $row['teacher_id']=(isset($row['teacher_id'])&&$row['teacher_id']!=null)?explode(",",$row['teacher_id']):array();
        $row['manager_id']=(isset($row['manager_id'])&&$row['manager_id']!=null)?explode(",",$row['manager_id']):array();
        $userModel = model('User');
        $data = array("args" => [[], $row['teacher_id'], $row['manager_id']]);
        $leftOptionsData = $userModel->getUserLists($data);
        $leftOptions = ($leftOptionsData == null) ? [] : $leftOptionsData["leftOptions"];
        $rightOptionsData = $userModel->getUserLists();
        $rightOptions = ($rightOptionsData == null) ? [] : $rightOptionsData["list"];
        $this->assignconfig("leftOptions", $leftOptions);
        $this->assignconfig("rightOptions", $rightOptions);
        $table_id = $row["table_id"] ? $row["table_id"] : trim($_REQUEST['table_id']);
        $this->assign("address_lv",$address_lv);
        $this->assign("table_id", $table_id);
        $this->assignconfig("table_id", $table_id);
        $this->assign("city_id", $city_id);
        $this->assign("school_id", $school_id);
        $this->assign("community_id", $community_id);
        return $this->view->fetch();

    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row=$this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL){
        $where="where 1=1";
        if($_SESSION['think']['admin']['group_id']!=1){
            $where.=" and city_id='{$_SESSION['think']['admin']['city_id']}'";
        }
        $page=1;
        $pagesize=50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn=preg_split("/\,/",$keyValue);
                    for($i=0;$i<count($nn);$i++) {
                        $where.= " and $keyField='{$nn[$i]}'";
                    }
                }
            }else{
                $where="where 1=1";
                if(isset($_REQUEST['city_id'])&&$_REQUEST['city_id']>0){
                    //$where.=" and city_id=".$_REQUEST['city_id'];
                }
            }
        }
        $sql="select id,__firstfield__ name from dev002_gxyusheng.fa_course_table_classplant $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

//        $r_name = model("School")->field("id,name")->where("id", "=", $_REQUEST['school_id'])->select();
//        if (empty($list)&&!empty($r_name)) {
//            $data = array(
//                "type" => "file",
//                "pid" => 0,
//                "name" => $r_name[0]['name']."学科",
//                "title" => $r_name[0]['name'],
//                "ismenu" => 0,
//                "createtime" => time(),
//                "updatetime" => time(),
//                "status" => 1,
//                "school_id" => $_REQUEST['school_id'],
//            );
//            $this->model->create($data);
//        }
//        $sql="select id,pid,name,title,status from dev002_gxyusheng.fa_course_table_classplant $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
//        $list = db()->query($sql);
//        $tree = Tree::instance();
//        $tree->init($list, 'pid');
//        $list = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.fa_course_table_classplant $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

    public function changeStatus($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

    public function export()
    {
        // 获取数据
        $list = $this->model->select();

        // 设置导出文件名
        $filename = '教学点下载' . date('YmdHis');

        // 设置表头
        $headers = [
            'ID', '项目名称', '班级'
        ];

        // 设置数据
        $data = [];
        foreach ($list as $item) {
            $ocation=model("Ocation")->get($item['id']);
            $courseable=model("Coursetable")->get($item['table_id']);
            $classes=model("Classes")->get($item['classes_id']);
            if($ocation&&$courseable&&$classes) {
                $data[] = [
                    $ocation['name'],
                    $courseable['name'],
                    $classes['name'],
                ];
            }
        }

        // 调用导出方法
        $this->exportExcel($filename, $headers, $data);
    }


    public function export2()
    {
        // 获取数据
        $list = $this->model->select();

        // 设置导出文件名
        $filename = '教学点下载' . date('YmdHis');

        // 设置表头
        $headers = [
            'Id',
            '项目名称',
            '班名',
            '教室',
            '课程',
            '老师',
            '日期',
            '周几',
            '时段',
            '课节',
            '备注',
            '操作',
        ];

// 设置数据
        $data = [];
        foreach ($list as $item) {
            $ocation = model("Ocation")->field("name")->get($item['id']);
            $courseable = model("Coursetable")->field("name")->get($item['table_id']);
            $classes = model("Classes")->field("name")->get($item['classes_id']);
            $data[] = [
                $item['id'],
                $item['project_name'],
                $classes['name'],
                $ocation['name'],
                $courseable['name'],
                $item['teacher_id'],
                $item['date'],
                $item['day_of_week'],
                $item['time_slot'],
                $item['class_period'],
                $item['remarks'],
                $item['operation'],
            ];
        }

        // 调用导出方法
        $this->exportExcel($filename, $headers, $data);
    }

    protected function exportExcel($filename, $headers, $data)
    {
        // 导出Excel文件
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        // 设置表头
        $sheet->fromArray($headers, null, 'A1');
        // 设置数据
        $sheet->fromArray($data, null, 'A2');

        // 设置列宽为内容自适应
        foreach (range('A', $sheet->getHighestColumn()) as $column) {
            $sheet->getColumnDimension($column)->setAutoSize(true);
        }

        // 设置响应头
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
        header('Cache-Control: max-age=0');
        // 输出文件
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }

}
